import datetime
import json
import os
import re
import sys

import requests

sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from aws_model.athena_submit import submit

# api url:http://doc.mymlsoft.com:3030/index.do#/168793046428607000201/front/interfaceDetail/169984132141312000134
get_setting_url = "http://hw-dev-envsplit.mymlsoft.com/gateway/datarate/record/abnormal/getSetting"
# get_setting_url = "http://hw-dev-envsplit.mymlsoft.com/gateway/datarate/record/abnormal/getSetting"

#api url:http://doc.mymlsoft.com:3030/index.do#/168793046428607000201/front/interfaceDetail/169983976939312000130
batch_save_url = "http://hw-dev-envsplit.mymlsoft.com/gateway/datarate/record/abnormal/batchSave"
# batch_save_url = "http://hw-dev-envsplit.mymlsoft.com/gateway/datarate/record/abnormal/batchSave"

token_header = {
    "token": "eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJyZW1vdGVKaUh1b0luZm8iLCJpZCI6Ijg5Iiwicm9sZSI6IlJPTEVfc2Vuc2l0aXplLFJPTEVfbG9naW5TdWNjZXNzIiwiZXhwIjoxNjY2MTYxODE2LCJjcmVhdGVkIjoxNjY2MTQ3NDE2MDY2LCJyb2xlSWQiOiI0NyJ9.hC85NLQsJBCuDMfM9cHYGoj7lvwyNZEywxeiB6j12kmgJ2HNnU6s3EX57J2mLRy2-rlJd93GNOFG6l37Ps68oQ"
}

tables = ['ods.iot_ac_mqtt']


def readable_file_size(bytes, precision):
    for unit in ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB']:
        if abs(bytes) < 1024.0:
            return '%s %s' % (format(bytes, '.%df' % precision), unit)
        bytes /= 1024.0
    return '%s %s' % (format(bytes, '.%df' % precision), 'Yi')


def data_size(directory, date):
    try:
        p = os.popen(f'aws s3 ls --summarize --recursive {directory}/p_date={date}')
        result = p.read()
        size = re.findall(r"Total Size: (\d+)", result)[0]
        p.close()
        return size
    except Exception as e:
        return '0'


def run():
    count_map = {}
    date = (datetime.datetime.today() + datetime.timedelta(hours=8) - datetime.timedelta(days=1)).strftime('%Y-%m-%d')

    # get warning material settings
    settings_json = json.loads(requests.get(url=get_setting_url, headers=token_header).text)

    # if request failed,return
    if settings_json["code"] != 200:
        print(settings_json)
        return

    # extract default value and special materials settings
    default_value = settings_json['data']['defaultValue']
    material_datas = settings_json['data']['materialDatas']
    special_materials = {}
    keys = []
    for one in material_datas:
        special_materials[one['material']] = one['warningData']
        keys.append(one['material'])

    # test
    # special_materials['8005482'] = 8000
    # keys.clear()
    # keys.append("8005482")

    for table in tables:
        # default warning daeta
        if len(keys) > 0:
            not_keys = "('" + "','".join(keys) + "')"
            not_in_sql = f" and material not in {not_keys}"
        else:
            not_in_sql = ""
        sql = f'''select sn,count(1) as nn from {table} where p_date = '{date}' {not_in_sql} group by sn having count(1) >= {default_value} '''
        print(sql)
        rs = submit(sql)
        for sn, count in rs['result']:
            count_map[sn] = count

        # special material warning data
        for key in keys:
            in_sql = f" and material='{key}'"
            sql = f'''select sn,count(1) as nn from {table} where p_date = '{date}' {in_sql} group by sn having count(1) >= {special_materials[key]} '''
            print(sql)
            rs = submit(sql)
            for sn, count in rs['result']:
                count_map[sn] = count

    send(count_map, date, type="url")


def send(map, date, type="qywx"):
    if type == "qywx":
        send_qxwx(map, date)
    elif type == "url":
        send_url(map, date)
    else:
        print("type error")


def send_url(map, date):
    msg = []
    for k, v in map.items():
        msg.append({"sn": k, "recordCount": v})
    j = json.dumps(msg)
    print(j)
    head = {
        "token": token_header["token"],
        'Content-Type': 'application/json'
    }
    response = requests.post(url=batch_save_url, data=j, headers=head)
    print(msg)
    print(response.text)
    print('已发送消息到url')


def send_qxwx(map, date):
    qywx_robot_url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=7ab519d4-02d4-4e85-a6f6-b066e56e195c"
    send_url = qywx_robot_url
    headers = {
        'Content-Type': 'application/json'
    }
    try:
        content = f'<font color=\"warning\">空调上报数据异常(>=配置条数):{date}</font>'
        for k, v in map.items():
            content = content + f"\n> {k}: <font color=\"comment\"> {v}条 </font> "
        msg = {
            "msgtype": 'markdown',
            "markdown": {'content': content}
        }
    except Exception as e:
        print(str(e))
        msg = {
            "msgtype": 'text',
            "text": {'content': f'执行错误,{str(map)}'}
        }
    print(msg)
    response = requests.post(url=send_url, data=json.dumps(msg), headers=headers)
    print(map)
    print(response)
    print('已发送消息到企业微信')


# 空调mqtt数据超过阈值设备通知
if __name__ == '__main__':
    run()
